<template>
	<div
		v-if="showMenu"
		class="context-menu-container"
		:style="{ left: left + 'px', top: top + 'px' }"
		ref="MenuContainer"
	>
		<AppContextMenu
			:items="contextMenus"
			@item-click="(item: IParam, event: MouseEvent) => { handleContextMenuItemClick(item, event) }"
		></AppContextMenu>
	</div>
</template>

<script setup lang="ts">
import { ContextMenuContainerProps } from './context-menu-container';
import { AppContextMenu } from '@/components/widgets/context-menu';
import { IParam } from '@/core';
const props = defineProps(ContextMenuContainerProps);
const emit = defineEmits<{
	(name: 'context-menu-item-click', value: any): void;
}>();

const MenuContainer = ref();

const showMenu = ref(false);

const left = ref(0);

const top = ref(0);

//open
const openMenu = (e: MouseEvent) => {
	var x = e.clientX;
	var y = e.clientY;
	top.value = y;
	left.value = x;
	showMenu.value = true;
};

//close
const closeMenu = () => {
	showMenu.value = false;
	emit('context-menu-item-click', {});
};

watch(showMenu, async (val) => {
	if (val) {
		document.body.addEventListener('click', closeMenu);
	} else {
		document.body.removeEventListener('click', closeMenu);
	}
});

const handleContextMenuItemClick = (item: IParam, event: MouseEvent) => {
	emit('context-menu-item-click', { item, event });
	showMenu.value = false;
};

defineExpose({
	openMenu,
	closeMenu,
});
</script>
